package plugins.detail;

import kd.bos.bill.BillShowParameter;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.ShowType;
import kd.bos.form.control.*;
import kd.bos.form.control.events.TimelineEvent;
import kd.bos.form.control.events.TimelineListener;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.sdk.plugin.Plugin;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.EventObject;
import java.util.List;

/**
 * 动态表单插件
 */
public class HuoDongTimeLine extends AbstractFormPlugin implements Plugin {
    // 时间轴控件标识（需在表单设计器中设置相同标识）
    private static final String TIMELINE_CTRL_KEY = "dcb4_timelineap1";

    // 新闻实体字段标识
    private static final String HuoDong_ENTITY = "dcb4_huodong";
    private static final String HuoDong_TITLE_FIELD = "dcb4_title";
    private static final String HuoDong_DATE_FIELD = "dcb4_date";

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);

        // 1. 添加时间轴点击监听器
        Timeline timeline = this.getView().getControl(TIMELINE_CTRL_KEY);
        if (timeline != null) {
            timeline.addTimelineListener(new TimelineListener() {
                @Override
                public void update(TimelineEvent timelineEvent) {
                    // 响应标签和内容区点击
                }

                @Override
                public void optionClick(TimelineOptionClickArg e) {
                    // 2. 处理节点点击事件
                    String newsId = e.getOptionKey();
                    openNewsDetail(newsId);
                }
            });
        }
    }

    private void openNewsDetail(String newsId) {
        // 3. 创建表单打开参数
        BillShowParameter showParameter = new BillShowParameter();
        showParameter.setFormId(HuoDong_ENTITY); // 新闻表单标识
        showParameter.setPkId(newsId);        // 设置新闻ID
        showParameter.getOpenStyle().setShowType(ShowType.Modal); // 模态窗口

        // 4. 打开新闻详情表单
        this.getView().showForm(showParameter);
    }

    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        loadNewsToTimeline();
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        // 当相关字段变化时刷新时间轴
        if (HuoDong_DATE_FIELD.equals(e.getProperty().getName()) ||
                HuoDong_TITLE_FIELD.equals(e.getProperty().getName())) {
            loadNewsToTimeline();
        }
    }

    private void loadNewsToTimeline() {
        try {
            // 1. 获取时间轴控件
            Timeline timeline = this.getView().getControl(TIMELINE_CTRL_KEY);

            // 关键修复：检查控件是否存在
            if (timeline == null) {
                this.getView().showTipNotification("时间轴控件未找到，请检查标识: " + TIMELINE_CTRL_KEY);
                return;
            }

            // 2. 查询最新4条新闻
            String selectFields = "id," + HuoDong_DATE_FIELD + "," + HuoDong_TITLE_FIELD + ",modifytime";
            QFilter[] filters = new QFilter[0]; // 可根据需要添加过滤条件
            String orderBy = "billno desc";
            int top = 4;

            DynamicObject[] newsList = BusinessDataServiceHelper.load(
                    HuoDong_ENTITY, selectFields, filters, orderBy, top
            );

            // 关键修复：检查查询结果
            if (newsList == null || newsList.length == 0) {
                this.getView().showTipNotification("未找到活动数据");
                return;
            }

            // 3. 构建时间轴数据
            List<TimelineOption> timelineOptions = new ArrayList<>();
            for (DynamicObject news : newsList) {
                TimelineOption option = new TimelineOption();
                String newsId = news.getString("id"); // 获取新闻ID

                // 获取日期和标题
                Date newsDate = news.getDate(HuoDong_DATE_FIELD);
                String title = news.getString(HuoDong_TITLE_FIELD);
                Date newsTime = news.getDate("modifytime");

                // 关键修复：检查日期是否为空
                if (newsDate == null) {
                    this.getView().showTipNotification("活动日期为空，跳过此记录");
                    continue;
                }

                // 关键修复：正确创建TimelineText对象
                // 创建日期标签
                TimelineText dateText = new TimelineText();
                dateText.setText(new LocaleString(formatDate(newsDate)));

                // 创建标题文本
                TimelineText titleText = new TimelineText();
                titleText.setText(new LocaleString(title));

                // 将Date格式化为字符串
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String dateStr = sdf.format(newsDate);
                SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm");
                String timeStr = sdf1.format(newsTime);

                // 创建LocaleString对象
                LocaleString localeDate = new LocaleString(dateStr);
                LocaleString localeTime = new LocaleString(timeStr);

                // 创建TimelineText
                TimelineText DateText = new TimelineText(localeDate, new TimeLineStyle("#212121"));

                // 设置时间节点标签
                TimelineLabelOption labelOption = new TimelineLabelOption(
                        DateText,  // 使用正确的LocaleString
                        new TimelineText(localeTime, new TimeLineStyle("#212121"))
                );
                option.setLabel(labelOption);

                TimelineContentOption contentOption = new TimelineContentOption(
                        titleText, // 使用标题文本
                        new ArrayList<>()
                );
                option.setContent(contentOption);

                // 5. 设置节点操作标识（关键步骤）
                List<TimelineOptionKey> optionKeys = new ArrayList<>();
                optionKeys.add(new TimelineOptionKey(new LocaleString("查看"), newsId));
                option.setOptionKeys(optionKeys);

                timelineOptions.add(option);
            }

            if (timelineOptions.isEmpty()) {
                this.getView().showTipNotification("没有有效的活动数据可展示");
                return;
            }

            // 4. 设置到时间轴控件
            timeline.setClientTimelineOptions(timelineOptions);


        } catch (Exception e) {
            this.getView().showTipNotification("加载活动时间轴失败: " + e.getMessage());
        }
    }

    // 日期格式化方法 (yyyy-MM-dd HH:mm)
    private String formatDate(Date date) {
        return new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm").format(date);
    }
}